#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import subprocess
from mj_parser.common_errors import CommonError


def run_execute(command):
    proc = subprocess.Popen(command,
                            stderr=subprocess.PIPE)
    return proc.wait(), proc.stderr.read()


def get_errors(error_string):
    lines = error_string.splitlines()
    error_lines = tuple(line for line in lines if line.find('Error') >= 0)
    if len(error_lines) > 0:
        return '\n'.join(error_lines)
    else:
        return error_string.strip()


def win32_command(command):
    status, error_string = run_execute(command)
    if status:
        errors = get_errors(error_string)
        raise CommonError(status, errors)